package com.lin.sppringbootdemo.controller;


import com.lin.sppringbootdemo.domain.ResultData;
import com.lin.sppringbootdemo.domain.TestLin;
import com.lin.sppringbootdemo.jpa.TestLinRepository;
import com.lin.sppringbootdemo.mapper.TestLinMapper;
import com.lin.sppringbootdemo.service.TestLinService;
import com.lin.sppringbootdemo.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Optional;

@Api("lin接口")
@Slf4j
@RestController
public class TestLinController {

    @Autowired
    private TestLinMapper testLinMapper;
    @Autowired
    private TestLinRepository testLinRepository;
    @Autowired
    private TestLinService testLinService;

    @ApiOperation("单个查询接口")
    @GetMapping("/user")
    public ResultData<String> index() {
        TestLin user = testLinMapper.selectByID(1);

        return ResultUtil.success(user);
    }

    @ApiOperation("单个查接口")
    @GetMapping("/one")
    public ResultData<String> selectOne() {
        Optional<TestLin> one = testLinRepository.findById(1);
        TestLin testLin = one.orElse(null);
        return ResultUtil.success(testLin);
    }

    @ApiOperation("增加接口")
    @PostMapping("/add")
    public ResultData<TestLin> add(@Valid TestLin testLin, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        log.info(testLin.toString());
        @Valid TestLin save = testLinRepository.save(testLin);
        return ResultUtil.success(save);
    }

    @ApiOperation("根据ID查询接口")
    @GetMapping("/getage/{id}")
    public ResultData<String> getAge(@PathVariable Integer id) throws Exception {
//        try {
//            testLinService.getAge(id);
//        } catch (Exception e) {
//            return ResultUtil.fail(e.getMessage());
//        }
        testLinService.getAge(id);
        return ResultUtil.success();
    }


}



